"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 导入导出、备份恢复工具支持M*兼容性
Case Name   : 使用gs_dump导出表，表和列大小写测试
Create At   : 2023.05.04
Owner       : z@wan005
Description :
    1.设置参数dolphin.lower_case_table_names为0
    2.创建兼容b库
    3.兼容b库下建表，表和列为大写
    4.使用gs_dump工具导出表为纯文本格式
    5.导入之前导出的数据到新库
    6.连接导入库查询表信息，表名不加双引号
    7.给导入表插入数据
    8.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.成功
    6.成功，表和列均为大写l
    7.成功，列名使用时不区分大小写
    8.成功
History     :modified by z@wan005，2023.08.18，修改step5
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class GsDump0015(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.dbuser_node = Node('PrimaryDbUser')
        self.constant = Constant()
        self.com = Common()
        self.db_name = "db_dump_0015"
        self.db_name_01 = "db_dump_0015_01"
        self.tb_name = "TB_DUMP_0015"
        self.dump_path = os.path.join(macro.DB_BACKUP_PATH, 'dump0015')
        self.log.info('--备份postgresql.conf文件--')
        cmd = f"cp " \
              f"{os.path.join(macro.DB_INSTANCE_PATH, 'postgresql.conf')} " \
              f"{os.path.join(macro.DB_INSTANCE_PATH, 'postgresql.conf_bk')}"
        self.log.info(cmd)
        msg = self.dbuser_node.sh(cmd).result()
        self.log.info(msg)

    def test_server_tools(self):
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        text = '----step1: 设置参数dolphin.lower_case_table_names为0 ' \
               'expect: 成功----'
        self.log.info(text)
        set_cmd = f"sed -i '$a\\dolphin.lower_case_table_names=0' " \
                  f"{os.path.join(macro.DB_INSTANCE_PATH, 'postgresql.conf')}"
        self.log.info(set_cmd)
        msg = self.dbuser_node.sh(set_cmd).result()
        self.log.info(msg)
        restart_msg = self.sh_primary.restart_db_cluster()
        self.log.info(restart_msg)
        status = self.sh_primary.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status)

        text = '----step2: 创建兼容b库 expect: 成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"create database {self.db_name} encoding 'UTF8' " \
                  f"dbcompatibility 'b';" \
                  f"drop database if exists {self.db_name_01};" \
                  f"create database {self.db_name_01} encoding 'UTF8' " \
                  f"dbcompatibility 'b';"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd)
        self.log.info(sql_result)
        self.assertEqual(2, sql_result.count(
            self.constant.CREATE_DATABASE_SUCCESS), '执行失败:' + text)

        text = '---step3: 兼容b库下建表，表和列为大写 expect: 成功---'
        self.log.info(text)
        sql_cmd = f'''drop table if exists {self.tb_name};
        create table {self.tb_name}(ID int not null  primary key \
        auto_increment comment '主键');'''
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=self.db_name)
        self.log.info(sql_result)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, sql_result,
                      '执行失败:' + text)

        text = '----step4: 使用gs_dump工具导出表为纯文本格式 expect: 成功----'
        self.log.info(text)
        gs_dump_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"gs_dump " \
                      f"-p {self.dbuser_node.db_port} " \
                      f"{self.db_name} -F p " \
                      f"-f {self.dump_path}"
        self.log.info(gs_dump_cmd)
        dump_msg = self.dbuser_node.sh(gs_dump_cmd).result()
        self.log.info(dump_msg)
        self.assertIn(f"dump database {self.db_name} successfully",
                      dump_msg, '执行失败:' + text)

        text = '----step5: 导入之前导出的数据到新库 expect: 成功----'
        self.log.info(text)
        gsql_cmd = f"source {macro.DB_ENV_PATH};" \
                   f"gsql -p {self.dbuser_node.db_port} " \
                   f"{self.db_name_01} -r -f {self.dump_path}"
        self.log.info(gsql_cmd)
        gsql_msg = self.dbuser_node.sh(gsql_cmd).result()
        self.log.info(gsql_msg)
        self.assertEqual(1, gsql_msg.count('CREATE TABLE'),
                         '执行失败:' + text)

        text = '-step6: 连接导入库查询表信息，表名不加双引号 ' \
               'expect: 成功，表和列均为大写--'
        self.log.info(text)
        sql_cmd = f"desc {self.tb_name};"
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=self.db_name_01)
        self.log.info(sql_result)
        self.assertIn(' ID    | integer | NO   | PRI | AUTO_INCREMENT |',
                      sql_result, '执行失败:' + text)

        text = '--step7: 给导入表插入数据 expect: 成功，列名使用时不区分大小写----'
        self.log.info(text)
        sql_cmd = f"insert {self.tb_name}(ID) values(2);" \
                  f"insert {self.tb_name}(id) values(12);"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=self.db_name_01)
        self.log.info(sql_result)
        self.assertEqual(2, sql_result.count('INSERT'), '执行失败:' + text)

    def tearDown(self):
        text = '---step8: 清理环境 expect: 成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"drop database if exists {self.db_name_01};"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname='postgres')
        self.log.info(sql_result)
        rm_cmd = f"rm -rf {self.dump_path}"
        self.log.info(rm_cmd)
        rm_msg = self.dbuser_node.sh(rm_cmd).result()
        self.log.info(rm_msg)
        rm = f"rm -rf " \
             f"{os.path.join(macro.DB_INSTANCE_PATH, 'postgresql.conf')};" \
             f"mv " \
             f"{os.path.join(macro.DB_INSTANCE_PATH, 'postgresql.conf_bk')} " \
             f"{os.path.join(macro.DB_INSTANCE_PATH, 'postgresql.conf')}"
        self.log.info(rm)
        rm_msg = self.dbuser_node.sh(rm).result()
        self.log.info(rm_msg)
        self.assertEqual(2,
                         sql_result.count(self.constant.DROP_DATABASE_SUCCESS))
        self.assertEqual('', rm_msg)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
